#include "junix.h"

typedef struct line_info
{
     unsigned lineno;
     char buf[LINE_MAX];
} line_info;

void do_regerror(int errcode,regex_t *pattern);

int main(int argc, char **argv)
{
     mtrace();

     if(argc!=3)
	  err_quit("Usage:%s regex file",argv[0]);

     char *regex = argv[1];
     char *file = argv[2];

     FILE *fp=fopen(file,"r");
     if(!fp)
	  err_quit("fopen error");

     regex_t pattern;
     int ret=regcomp(&pattern, regex, REG_EXTENDED|REG_NEWLINE);
     if(ret)
	  do_regerror(ret,&pattern);

     regmatch_t *mt = alloca((pattern.re_nsub+1)*sizeof(regmatch_t) );
     line_info li={0, {'\0'} };

     while( fgets(li.buf, LINE_MAX,fp) != NULL)
     {
	  li.lineno++;

	  ret=regexec(&pattern,li.buf,pattern.re_nsub+1,mt,0);

	  if(!ret)
	       printf("%6.6d: %s",li.lineno, li.buf);
	  else if(ret!=REG_NOMATCH)
	       do_regerror(ret,&pattern);
     }

     regfree(&pattern);
     fclose(fp);

     exit(0);
}

void do_regerror(int errcode,regex_t *pattern)
{
     size_t len=regerror(errcode,pattern,NULL,0);
     char *ebuf = alloca(len*sizeof(char));

     regerror(errcode,pattern,ebuf,len);

     err_quit("Regex error:%s",ebuf);
}
